package com.chen.controller;

import com.chen.entity.UserEntity;
import com.chen.service.UserService;
import com.chen.utils.ChenJdbcUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public ModelAndView loginUser(@RequestParam("phone") String phone, @RequestParam("pwd") String pwd) {
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(pwd)) {
            return new ModelAndView("error", "errorMsg", "错误原因：账号密码为空值");
        }
        //用jdbc查询SQL语句
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            connection = ChenJdbcUtils.getConnection();
            statement = connection.prepareStatement("select * from chen_user where phone=? and pwd=? and is_delete=0");
            statement.setString(1, phone);
            statement.setString(2, pwd);
            resultSet = statement.executeQuery();
            UserEntity userEntity = userService.getByPhoneUser(phone);
            if (resultSet.next()) {
                return new ModelAndView("redirect:/showFlight", "phone", userEntity.getPhone());
            } else {
                //登陆失败
                return new ModelAndView("error", "errorMsg", "账号或密码错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ModelAndView("error", "errorMsg", "系统错误或该用户不存在");
        } finally {
            ChenJdbcUtils.closeConnection(resultSet, statement, connection);
        }
    }


    @PostMapping("/register")
    public ModelAndView loginUser(@RequestParam("phone") String phone, @RequestParam("pwd") String pwd, @RequestParam("name") String name) {
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(pwd) || StringUtils.isEmpty(name)) {
            return new ModelAndView("error", "errorMsg", "错误原因：账号密码姓名为空值");
        }
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        //2.调用jdbc api 在数据库插入数据
        try {
            connection = ChenJdbcUtils.getConnection();
            ChenJdbcUtils.beginTransaction(connection);   //开启事务
            //需要判断该用户名是否已重复存在，如果存在则不能注册
            preparedStatement = connection.prepareStatement("select * from chen_user where name=?;");
            preparedStatement.setString(1, name);
            resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
                return new ModelAndView("error", "errorMsg", "用户名已存在");
            }
            preparedStatement = connection.prepareStatement("select * from chen_user where phone=?;");
            preparedStatement.setString(1, phone);
            resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
                return new ModelAndView("error", "errorMsg", "手机号已存在");
            }

            //如果不存在
            String insertSql = "INSERT INTO `chen`.`chen_user` (`id`, `name`, `pwd`, phone, is_delete)" + " VALUES (null, ?, ?, ?, 0);";
            preparedStatement = connection.prepareStatement(insertSql);
            preparedStatement.setString(1, name);
            preparedStatement.setString(2, pwd);
            preparedStatement.setString(3, phone);
            int result = preparedStatement.executeUpdate();//执行 insert sql 语句
            if (result <= 0) {
                return new ModelAndView("error", "errorMsg", "注册失败");
            }
            ChenJdbcUtils.commitTransaction(connection);
            return new ModelAndView("login");
            //关闭事务
        } catch (Exception e) {
            e.printStackTrace();
            // 如果报错需要回滚事务
            ChenJdbcUtils.rollBackTransaction(connection);
            return new ModelAndView("error", "errorMsg", "注册失败");
        } finally {
            //释放资源
            ChenJdbcUtils.closeConnection(null, preparedStatement, connection);
        }
    }


    @RequestMapping("/deleteUser")
    public ModelAndView deleteUser(@RequestParam("phone") String phone) throws ServletException, IOException {
        if (phone == null || phone == "") {
            //跳转到错误页面，客户端传递有误
            return new ModelAndView("error", "errorMsg", "phone的值为空");
        }
        try {
            int result = userService.updateDeleteByPhone(phone);
            if (result > 0) {
                //如果删除成功，则跳转(转发)到 /showFlight 页面
                return new ModelAndView("index");
            } else {
                //如果删除失败，则跳转(转发)到 error.jsp 页面
                return new ModelAndView("error", "errorMsg", "删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ModelAndView("error", "errorMsg", "系统异常");
        }
    }
}
